package com.javaweb.admin.config;

import com.javaweb.admin.entity.Scheduled;
import com.javaweb.admin.service.AbstractJob;
import com.javaweb.admin.service.ScheduledService;
import com.javaweb.common.config.CommonConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * @author liangxuelong
 * @version 1.0
 * @description: 定时任务配置类
 * @date 2021/8/25 9:40
 */
@Configuration
@EnableScheduling
public class ScheduledConfig implements SchedulingConfigurer {

    @Autowired
    private ApplicationContext context;
    @Autowired
    private ScheduledService scheduledService;
    public static ConcurrentHashMap<String, ScheduledFuture> cache= new ConcurrentHashMap<String, ScheduledFuture>();
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        //数据库查询到所有的定时任务
        if(CommonConfig.enableSchedule) {
            List<Scheduled> scheduledList = scheduledService.findAllScheduled();
            //创建定时任务
            for (Scheduled scheduled : scheduledList) {
                AbstractJob task = null;
                try {
                    task = (AbstractJob) context.getBean(Class.forName(scheduled.getClasspath()));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                if (scheduled.getStatus() == 1) {
                    task.createJob(scheduled.getCron());
                }
            }
        }
    }

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
        executor.setPoolSize(20);
        executor.setThreadNamePrefix("taskExecutor-");
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        return executor;
    }
}


